import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;

import br.ufpr.infra.ConsultaRemota;


public class ConsultarDadosRemotos {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Properties p = new Properties();
			configura(p);
			
			ConsultaRemota cR = (ConsultaRemota)new InitialContext(p).lookup("infraestrutura");
			List<String> listaColunas; 
			List<Object[]> linhas;
			
			int cont=5;
			StringBuffer sql = new StringBuffer();
			for(String item : args ) {
				System.out.print(item + " ");
				sql.append(item + " ");
				cont--;
				if (cont <= 0 ) {
					System.out.println("");
					cont=5;
				}
			}
			System.out.println("");
			cR.efetuaConsulta(sql.toString());
			listaColunas = cR.recuperaColunas();
			linhas = cR.recuperaDados();
			
			System.out.println("-------------------------------------------------------");
			
			int lenColunas[] = new int[listaColunas.size()];
			int i=0;
			for ( String coluna : listaColunas ) {
				System.out.print(coluna + "\t|\t");
				lenColunas[i++]=coluna.length();
			}
			System.out.println("");
			
			for( Object item[] : linhas ){
				i=0;
				for ( Object o : item ) {
					System.out.print(garante(o, lenColunas[i++]) + "\t|\t");
				}
				System.out.println("");
			}
			
			System.out.println("-------------------------------------------------------");
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		

	}

	private static String garante(Object o, int qtd) {
		String resultado = o.toString();
		if (resultado.length() > qtd) {
			return resultado.substring(0, qtd);
		} 
		StringBuffer sb = new StringBuffer();
		for(int i=0; i<qtd; i++) {
			sb.append(" ");
		}
		sb.append(resultado);
		return sb.toString().substring(resultado.length());
	}
	
	private static void configura(Properties props) {
		props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
		props.setProperty(Context.URL_PKG_PREFIXES, "com.sun.enterprise.naming");
		props.setProperty(Context.STATE_FACTORIES, "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
		// servidor
		props.setProperty("org.omg.CORBA.ORBInitialHost", "192.168.0.100");
		// porta do servidor
		props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
		
	}
 	
}
